//
//  XGMineViewController.swift
//  TodayNews
//
//  Created by monkey on 2020/2/3.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import SwiftTheme

/// 头部视图高度
let XGLoginHeaderViewHeight: CGFloat = 260.0

class XGMineViewController: UITableViewController
{
    // MARK: 控制器生命周期方法

    override func viewDidLoad()
    {
        super.viewDidLoad()

        // 设置tableView
        setUpTableView()
        // 加载数据
        loadData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(followRelationChangedNotification), name: kFollowRelationChangedNotification, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }
            
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
        
    /// 视图模型
    private let viewModel: XGMineViewModel = XGMineViewModel()
    /// 头部视图
    private lazy var headerView: XGLoginHeaderView = { [weak self] in
        let headerView = XGLoginHeaderView(frame: CGRect(x: 0, y: 0, width: TodayNews_Screen_Width, height: XGLoginHeaderViewHeight))
        return headerView
    }()
}

// MARK: 数据源和代理方法

extension XGMineViewController
{
    /// 多少组
    override func numberOfSections(in tableView: UITableView) -> Int
    {
        return viewModel.items?.count ?? 0
    }
    
    /// 每组多少行
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return viewModel.items?[section].count ?? 0
    }
    
    /// 每行内容
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        if indexPath.section == 0 && indexPath.row == 0 {
            let cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGMineConcernTableViewCell
            cell.concernUsers = viewModel.concernUsers
            cell.delegate = self
            return cell
        } else {
            let cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGMineItemTableViewCell
            cell.itemModel = viewModel.items?[indexPath.section][indexPath.row]
            return cell
        }
    }
    
    // 每组头部视图
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
    {
        let view = tableView.xg_dequeueReusableHeaderFooterView() as XGMineTableHeaderFooterView
        return view
    }
    
    /// cell行高
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        if indexPath.section == 0 && indexPath.row == 0 {
            return ((viewModel.concernUsers?.count ?? 0) <= 1) ? 44.0 : 44.0 + 64
        } else {
            return 44.0
        }
    }
    
    /// 选中cell
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: false)

        // 系统设置
        if indexPath.section == 3 && indexPath.row == 1 {
            let settingViewController = XGSystemSettingTableViewController(plistName: "TodayNews_system_setting.plist")
            navigationController?.pushViewController(settingViewController, animated: true)
        }
    }
    
    /// tableView滚动
    override func scrollViewDidScroll(_ scrollView: UIScrollView)
    {
        headerView.offsetY = scrollView.contentOffset.y
    }
}

// MARK: XGMineConcernTableViewCellDelegate

extension XGMineViewController: XGMineConcernTableViewCellDelegate
{
    func concernUserDidSelected(_ concernUser: XGConcernUserModel)
    {
        let userDetailViewController = XGUserDetailViewController(userId: concernUser.userid)//UserDetailViewController(userId: concernUser.userid)
        navigationController?.pushViewController(userDetailViewController, animated: true)
    }
}

// MARK: 私有扩展

private extension XGMineViewController
{
    /// 关注用户关系发送改变通知监听
    @objc func followRelationChangedNotification() -> Void
    {
        viewModel.fetchConcernUsers { (isSuccess) in
            isSuccess ? self.tableView.reloadSections(IndexSet(integer: 0), with: .fade) : ()
        }
    }
    
    /// 设置tableView
    func setUpTableView() -> Void
    {
        tableView.xg_registerCell(cellType: XGMineConcernTableViewCell.self)
        tableView.xg_registerCell(cellType: XGMineItemTableViewCell.self)
        tableView.xg_registerHeaderFooterView(viewType: XGMineTableHeaderFooterView.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.tableFooterView = UIView()
        tableView.sectionHeaderHeight = 10.0
        tableView.tableHeaderView = headerView
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: TodayNews_TabBar_Height, right: 0)
        tableView.theme_backgroundColor = "colors.cell_background"
        tableView.theme_separatorColor = "colors.cell_separator"
    }
    
    /// 加载数据
    func loadData() -> Void
    {
        // 获取我的列表数据
        viewModel.fetchMineList { (isSuccess) in
            if isSuccess {
                self.tableView.reloadData()
                // 获取我的关注数据
                self.viewModel.fetchConcernUsers { (isSuccess) in
                    isSuccess ? self.tableView.reloadSections(IndexSet(integer: 0), with: .fade) : ()
                }
            }
        }
    }
}

// MARK: - XGMineTableHeaderFooterView

class XGMineTableHeaderFooterView: UITableViewHeaderFooterView,XGRegisterReusableViewProtocol
{
    override init(reuseIdentifier: String?)
    {
        super.init(reuseIdentifier: reuseIdentifier)
        
        let backgroundView = UIView()
        backgroundView.theme_backgroundColor = "colors.cell_separator"
        self.backgroundView = backgroundView
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
